<template>
  <t-dialog
    :header="`${header}-${isEdit ? '修改承担项目' : '添加承担项目'}`"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    confirmBtn="确定"
    :onConfirm="onSubmit"
    width="80%"
    top="1%"
  >
    <div id="main">
      <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium"> </t-loading>
      <div>
        <!-- 基本信息 -->
        <t-form ref="form" :data="formData" :rules="rules" labelWidth="180px">
          <t-row style="align-items: stretch; width: 99%" :gutter="14">
            <t-col :span="12">
              <t-card class="step-card" size="medium" title="基本信息">
                <t-row style="align-items: stretch" :gutter="14">
                  <t-col :span="6">
                    <t-form-item label="投入年份：" name="year">
                      <t-date-picker style="width: 390px" v-model="formData.year"></t-date-picker>
                    </t-form-item>
                    <t-form-item label="项目名称：" name="name">
                      <t-input
                        style="width: 390px"
                        placeholder="请输入项目名称"
                        clearable
                        v-model="formData.name"
                      ></t-input>
                    </t-form-item>
                    <t-form-item label="项目金额（万元）：" name="projectMoney">
                      <t-input-number
                        style="width: 390px"
                        placeholder="请输入项目金额（万元）"
                        clearable
                        v-model="formData.projectMoney"
                      ></t-input-number>
                    </t-form-item>
                    <t-form-item label="项目级别：" name="projectLevel">
                      <t-select
                        style="width: 390px"
                        placeholder="请选择项目级别"
                        :options="dict.type.project_level"
                        v-model="formData.projectLevel"
                      >
                      </t-select>
                    </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item label="项目负责人：" name="leaderName">
                      <t-input
                        style="width: 390px"
                        placeholder="请输入项目负责人"
                        clearable
                        v-model="formData.leaderName"
                      ></t-input>
                    </t-form-item>
                    <t-form-item label="承担单位：" name="deptName">
                      <t-input
                        style="width: 390px"
                        placeholder="请输入承担单位"
                        clearable
                        v-model="formData.deptName"
                      ></t-input>
                    </t-form-item>
                    <t-form-item ref="reviseNum" label="备注：" name="note">
                      <t-input style="width: 390px" clearable v-model="formData.note"></t-input>
                    </t-form-item>
                  </t-col>
                </t-row>
              </t-card>
            </t-col>
          </t-row>
        </t-form>
      </div>
    </div>
  </t-dialog>
</template>

<script>
import { getDictList } from '@/api/system/dict/data';
import { getFiles } from '@/api/common';

import { TODAY } from '@/utils/date';
import dayjs from 'dayjs';
import { getIdCardBirthday } from '@/utils/common';

export default {
  name: 'people-apply',
  components: {},
  dicts: ['formulate_type', 'standard_category', 'standard_property', 'project_level'],
  props: {
    header: String,
    objId: [String, Number],
    row: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      profTitOptions: [],
      visible: true,
      deptMenuOptions: [],
      dictTypes: {},
      nameOptions: [],
      leaderLoading: false,
      subBtnLoading: false,
      reviseNumDisable: true,
      active: 1,
      subType: 2,
      applyLoading: false,
      maxlength: 1000,
      lengthLimitObj: {
        description: 0,
      },
      tinymceFlag: 1,
      dayjs,
      isEdit: false,
      formData: {
        id: null,
        platformId: this.objId,
        year: '',
        name: '',
        projectMoney: '',
        projectLevel: '',
        leaderName: '',
        deptName: '',
        note: '',
      },
      rules: {
        year: [
          {
            required: true,
            message: '投入时间不能为空',
          },
        ],
        name: [
          {
            required: true,
            message: '项目名称不能为空',
          },
        ],
        projectMoney: [
          {
            required: true,
            message: '项目金额（万元）不能为空',
          },
        ],
        projectLevel: [
          {
            required: true,
            message: '项目级别不能为空',
          },
        ],
        leaderName: [
          {
            required: true,
            message: '项目负责人不能为空',
          },
        ],
        deptName: [
          {
            required: true,
            message: '承担单位不能为空',
          },
        ],
      },
    };
  },
  async mounted() {
    await this.getDataTypes();
  },
  async created() {
    await this.getDeptTreeSelect(this.$store.state.user.deptId);
    this.isEdit = !!this.row.id
    Object.assign(this.formData, this.row)
    // 判断路由有没有id传过来
    // 有id则是修改需要回显数据，无id则是新增
  },
  methods: {
    onProfTitIdChange(val, content) {
      this.formData.profTit = content.node.data.level;
    },
    getDataTypes() {
      return getDictList([
        'project_type',
        'subject_classification',
        'sys_user_sex',
        'prof_tit',
        'degree',
        'education',
        'duty',
        'platform_type',
        'expect_result_type',
      ])
        .then((response) => {
          this.dictTypes = response.data;
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== '') {
        this.formData.birthDate = birthday.slice(0, 7);
      }
    },
    onLeaderNameChange(val, content) {
      const index = this.nameOptions.findIndex((val) => content?.option?.id === val.id);
      this.nameOptions[index].label = this.nameOptions[index].name;
      this.$set(this.nameOptions, index, this.nameOptions[index]);
      // Object.assign(this.formData.projectLeader, content.option)
      const oldId = this.formData.id;
      let year = this.formData.year;
      Object.assign(this.formData, content.option || this.nameOptions[index]);
      this.formData.year = year;
      this.formData.id = oldId;
    },
    createProjectLeaderOptions(value) {
      this.nameOptions.push({
        label: `${value}`,
        value,
        name: value,
      });
    },
    remoteProjectLeaderMethod(search) {
      this.leaderLoading = true;
      this.$api.system.member
        .searchList({ name: search })
        .then((response) => {
          this.nameOptions = response.data.map((val) => ({
            ...val,
            label: `${val.name}-${val.idCard}`,
            value: `${val.name}-${val.idCard}`,
          }));
          this.leaderLoading = false;
        })
        .catch((e) => {
          this.leaderLoading = false;
          this.$message.error(e.toString());
        });
    },
    getDeptTreeSelect() {
      return this.$api.system.dept
        .treeSelectAllIn()
        .then((response) => {
          this.deptMenuOptions = response.data;
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    filterByTree(val, tree, children = 'children', id = 'id', label = 'label') {
      let text = '';
      const convert = (arr) => {
        arr.filter((item) => {
          if (item[id] === val) {
            text = item[label];
          } else if (item[children]) {
            return convert(item[children]);
          }
          return false;
        });
      };
      convert(tree);
      return text;
    },
    onSubmit() {
      this.$refs.form.validate().then(async (validateResult) => {
        if (validateResult === true) {
          // 路由有id修改，没有新增
          if (this.isEdit) {
            const message = '修改成功';
            this.subBtnLoading = true;
            this.$api.kjpt.haveProject
              .edit(this.formData)
              .then((response) => {
                this.subBtnLoading = false;
                this.$message.success(message);
                this.$emit('reload');
                this.closeDialog();
              })
              .catch((e) => {
                this.subBtnLoading = false;
                this.$message.error(e.toString());
              });
          } else {
            const message = '提交成功';
            this.subBtnLoading = true;
            this.$api.kjpt.haveProject
              .add(this.formData)
              .then((response) => {
                this.subBtnLoading = false;
                this.$message.success(message);
                this.$emit('reload');
                this.closeDialog();
              })
              .catch((e) => {
                this.subBtnLoading = false;
                this.$message.error(e.toString());
              });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    closeDialog() {
      this.$emit('update:visible', false);
    },
  },
};
</script>
